import React, {Component} from "react";
import {inject, observer} from "mobx-react";
import Search from "antd/es/input/Search";
import {Table as BTable} from "react-bootstrap"
import {Button, Descriptions, Modal, Pagination, Table} from "antd";
import Text from "antd/es/typography/Text";

export default @inject('store') @observer
class DataSearch extends Component {
    seedColumns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: '创建时间',
            dataIndex: 'CreatedAt',
            key: 'CreatedAt',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: 'Url',
            dataIndex: 'url',
            key: 'url',
        },
        {
            title: '解析方法名',
            dataIndex: 'function_name',
            key: 'function_name',
        },
    ];

    limit = 5;

    constructor(props) {
        super(props);
        this.state = {
            selectSeedVisible: false,
            seeds: [],
            seedsCurrent: 0,
            seedsCount: 0,
            selectedSeed: null,

            columns: [],
            data: null,

            resultCurrent: 1,
            resultCount: 0,
            selectedItem: null,
            selectedItemVisible: false,
            resultColumns: [],

            // headers: [],
            header: null,
            body: null,
        }
        ;
    }

    selectSeed() {
        this._getSeeds(0);
        this.setState({selectSeedVisible: true})
    }

    selectSeedOK() {
        window.$http.postForm("/columns/get", {
            seed_id: this.state.selectedSeed.ID,
        }).then(res => {
            if (res.status === 10000) {
                // JSON.parse(res.columns)
                console.log("columns:", res.columns.value);
                this.setState({
                    // columns: JSON.parse(res.columns.value),
                    selectSeedVisible: false
                });
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
    }

    _getSeeds(offset) {
        window.$http.postForm("/seed/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({seeds: res.seeds, seedsCount: res.count});
                console.log("settings", res.settings);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    _search(value, offset) {
        this.setState({queryValue: value});
        window.$http.postForm("/data/search", {
            seed_id: this.state.selectedSeed.ID,
            query: value,
            limit: this.limit,
            offset: offset
        }).then(res => {
            if (res.status === 10000) {
                // console.log("result", res.result);
                console.log("columns", res.columns);
                this.setState({resultColumns: res.columns, resultCount: res.count});
                // this.setState({columns: res.columns, result: res.result});
                this.table(JSON.parse(res.columns), res.result);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });

    }

    table(header, items) {
        let tHeaderTrs;
        tHeaderTrs = <tr key={1}>
            {header.map((h, i) => {
                return <th key={i}><Text>{h.value}</Text></th>
            })}
        </tr>;


        let tBodyTrs;
        tBodyTrs = items.map((i, idx) => {
            let js = JSON.parse(i._source.result);
            return <tr key={idx} onClick={() => this.detail(i)}>
                {
                    header.map((h, i) => {
                        const maxLen = 15;
                        let text;
                        if (typeof js[h.key] === "string") {
                            if (js[h.key].length > maxLen)
                                text = js[h.key].substring(0, maxLen) + '...';
                            else
                                text = js[h.key]
                        } else {
                            text = js[h.key]
                        }
                        return <td key={i}><Text>{text}</Text></td>
                    })
                }
            </tr>
        });
        // console.log("tHeaderTrs", tHeaderTrs);
        // console.log("tBodyTrs", tBodyTrs);
        this.setState({header: tHeaderTrs, body: tBodyTrs});
    }

    detail(item) {
        console.log("item", item);
        this.setState({selectedItem: item, selectedItemVisible: true})
    }

    item(columns, item) {
        let columnsObj = JSON.parse(columns);
        let itemSource = item._source;
        let itemSourceResult = JSON.parse(item._source.result);
        console.log("item", item);
        return <>
            <Descriptions.Item label={'ID'}>
                {itemSource.ID}
            </Descriptions.Item>
            <Descriptions.Item label={'创建时间'} span={2}>
                {itemSource.CreatedAt}
            </Descriptions.Item>
            <Descriptions.Item label={'Url'} span={3}>
                {itemSource.url}
            </Descriptions.Item>
            <Descriptions.Item label={'参数'} span={3}>
                {itemSource.params}
            </Descriptions.Item>
            {
                columnsObj.map((i, idx) => {
                    return <Descriptions.Item key={idx} label={i.value}>
                        {itemSourceResult[i.key]}
                    </Descriptions.Item>
                })
            }
        </>
    }

    render() {
        return (
            <div style={{width: '100%'}}>
                <Button type={"primary"} style={{marginBottom: 10}} onClick={() => this.selectSeed()}>选择任务</Button>
                {
                    this.state.selectSeedVisible ?
                        <Modal visible={this.state.selectSeedVisible} closable={false} width={1000}
                               onOk={() => this.selectSeedOK()}
                               onCancel={() => this.setState({selectSeedVisible: false, selectedSeed: null})}
                        >
                            <Table rowKey={record => record.ID} columns={this.seedColumns} dataSource={this.state.seeds}
                                   pagination={{
                                       total: this.state.seedsCount,
                                       current: this.state.seedsCurrent,
                                       pageSize: this.limit,
                                       onChange: (page) => {
                                           this.setState({current: page});
                                           this._getSeeds((page - 1) * this.limit);
                                       }
                                   }}
                                   rowSelection={{
                                       type: 'radio',
                                       onChange: (selectedRowsKey, selectedRows) => {
                                           this.setState({
                                               selectedSeed: selectedRows[0],
                                           });
                                       },
                                   }}/>
                        </Modal> : null
                }
                {
                    !this.state.selectedSeed ?
                        <Text type={"warning"} style={{marginLeft: 10}}>请先选择需查询的任务</Text> : null
                }
                {
                    this.state.selectedSeed ?
                        <div style={{marginBottom: 10}}>
                            <Descriptions bordered size={"small"} column={4}>
                                <Descriptions.Item label="ID">{this.state.selectedSeed.ID}</Descriptions.Item>
                                <Descriptions.Item label="名称">{this.state.selectedSeed.name}</Descriptions.Item>
                                <Descriptions.Item label="Url">{this.state.selectedSeed.url}</Descriptions.Item>
                                <Descriptions.Item
                                    label="解析方法名">{this.state.selectedSeed.function_name}</Descriptions.Item>
                            </Descriptions>
                            {/*<Text>ID:{this.state.selectedSeed.ID}</Text>*/}
                        </div> : null
                }
                <Search placeholder={'请输入需要查询的内容'} size={"large"}
                        enterButton={'查询'} style={{marginBottom: 10}}
                        onSearch={(value) => this._search(value, 0)}
                />
                {
                    this.state.header ?
                        <div>
                            <BTable responsive
                                    striped bordered hover>
                                <thead>
                                {this.state.header}
                                </thead>
                                <tbody>
                                {this.state.body}
                                </tbody>
                            </BTable>
                            <Pagination style={{marginTop: 5, float: "right"}}
                                        pageSize={this.limit} defaultCurrent={1}
                                        onChange={(page) => {
                                            this.setState({resultCurrent: page});
                                            this._search(this.state.queryValue, (page - 1) * this.limit);
                                        }}
                                        total={this.state.resultCount} current={this.state.resultCurrent}/>
                        </div>
                        : null
                }
                {
                    this.state.selectedItem ?
                        <Modal visible={this.state.selectedItemVisible} footer={null} width={'80%'}
                               onCancel={() => this.setState({selectedItemVisible: false, selectedItem: null})}
                        >
                            <Descriptions bordered>
                                {
                                    this.item(this.state.resultColumns, this.state.selectedItem)
                                }
                            </Descriptions>
                        </Modal> : null
                }
            </div>
        )
    }
}